package com.mingtu.dzpatrol.base;

import android.app.Activity;
import android.app.Application;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.bytedance.boost_multidex.BoostMultiDex;
import com.bytedance.boost_multidex.Result;
import com.luck.picture.lib.app.IApp;
import com.luck.picture.lib.app.PictureAppMaster;
import com.luck.picture.lib.basic.PictureSelectionCameraModel;
import com.luck.picture.lib.basic.PictureSelectionModel;
import com.luck.picture.lib.basic.PictureSelectionPreviewModel;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.config.VideoQuality;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.engine.PictureSelectorEngine;
import com.luck.picture.lib.engine.UriToFileTransformEngine;
import com.luck.picture.lib.interfaces.OnBitmapWatermarkEventListener;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.style.BottomNavBarStyle;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.SelectMainStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DateUtils;
import com.luck.picture.lib.utils.DensityUtil;
import com.luck.picture.lib.utils.PictureFileUtils;
import com.luck.picture.lib.utils.SandboxTransformUtils;
import com.lxj.xpopup.XPopup;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpHeaders;
import com.lzy.okgo.model.HttpParams;
import com.mingtu.dzpatrol.R;
import com.mingtu.dzpatrol.engine.ExoPlayerEngine;
import com.mingtu.dzpatrol.engine.IjkPlayerEngine;
import com.mingtu.dzpatrol.http.OKHttpUpdateHttpService;
import com.mingtu.dzpatrol.photo.GlideEngine;
import com.mingtu.dzpatrol.photo.PictureSelectorEngineImp;
import com.mingtu.dzpatrol.utils.ImageUtil;
import com.mingtu.dzpatrol.utils.MyLogUtil;
import com.mingtu.dzpatrol.utils.SPTools;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.xuexiang.xupdate.XUpdate;
import com.xuexiang.xupdate.entity.UpdateError;
import com.xuexiang.xupdate.listener.OnUpdateFailureListener;
import com.xuexiang.xupdate.logs.ILogger;
import com.xuexiang.xupdate.utils.UpdateUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;
import top.zibin.luban.OnRenameListener;

/**
 * @ClassName :
 * @Author : wkk
 * @Date : 2020/4/26 11:35:18
 * @Email : 1281573890@qq.com
 * @Eescription :
 */
public class BaseApplication extends MultiDexApplication implements IApp {
    private static BaseApplication application = null;
    private static Context mContext;
    private static Boolean isDebug = true;
    private static RequestOptions requestOptions;
    private static PictureSelectorStyle selectorStyle;
    private static PictureSelectionModel selectionModel;
    private BaseActivity baseActivity;
    private static int chooseMode = SelectMimeType.ofAll();
    private String TAG = "BaseApplication";
    //    private ReportedEventDao reportedEventDao;
    private static PictureSelectionCameraModel cameraModel;
    private static PictureSelectionPreviewModel previewModel;
    private static HttpLoggingInterceptor loggingInterceptor;

    @Override
    public void onCreate() {
        super.onCreate();
        requestOptions = new RequestOptions() //Glide 使用
                .centerCrop()
                .error(R.mipmap.img_data_error)
                .skipMemoryCache(false) //解决刷新闪烁的问题
                .diskCacheStrategy(DiskCacheStrategy.ALL); //全部使用磁盘缓存

        mContext = getApplicationContext();
        application = this;
        initSmartRefresh();
        initOkGo();
        initUpdate();
        initLog();

        //相册有关设置，顺序不能变
        PictureSelector();
        setDefaultStyle();
//        initLog();
        Thread.setDefaultUncaughtExceptionHandler(new OwnUncaughtExceptionHandler());//捕获全局异常

        //播放器绘制模式
//        GSYVideoType.setRenderType(GSYVideoType.SUFRACE);

        registerActivityLifecycleCallbacks(new myActivityLifecycleCallbacks()); //监听器  来监听 Activity 的启动情况

        XPopup.setPrimaryColor(getResources().getColor(R.color.colorPrimary));


        //创建数据库
//        ReportedEventDatabase reportedEventDatabase = Room.databaseBuilder(this, ReportedEventDatabase.class, "reported_event_database")
//                .allowMainThreadQueries()
//                .fallbackToDestructiveMigration()
//                .build();
//
//        reportedEventDao = reportedEventDatabase.getReportedEventDao();


    }

    private class myActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {

        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {

            if (activity instanceof BaseActivity) {
                baseActivity = (BaseActivity) activity;
            }
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
            baseActivity = null;
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {

        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        boolean useBoostMultiDex = true;
        long start = System.currentTimeMillis();
        if (useBoostMultiDex) {
            Result result = BoostMultiDex.install(base);//字节跳动
            if (result != null && result.fatalThrowable != null) {
                Log.e("BMD", "exception occored " + result.fatalThrowable);
            }
        } else {
            MultiDex.install(this);
        }
    }


    @Override
    public Context getAppContext() {
        return application;
    }

    @Override
    public PictureSelectorEngine getPictureSelectorEngine() {
        return new PictureSelectorEngineImp();
    }

    public static Context getContext() {
        return mContext;
    }

    public static BaseApplication getBaseApplication() {
        return application;
    }

    public static RequestOptions getRequestOptions() {
        return requestOptions;
    }

    private void initSmartRefresh() {


        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色

                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

    }

    private void initOkGo() {
        //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
        HttpHeaders headers = new HttpHeaders();
        headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文，不允许有特殊字符
        headers.put("commonHeaderKey2", "commonHeaderValue2");
        HttpParams params = new HttpParams();
        params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
        params.put("commonParamsKey2", "这里支持中文参数");
        //----------------------------------------------------------------------------------------//

        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        //log相关
        loggingInterceptor = new HttpLoggingInterceptor("wkk");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //第三方的开源库，使用通知显示当前请求的log，不过在做文件下载的时候，这个库好像有问题，对文件判断不准确
        //builder.addInterceptor(new ChuckInterceptor(this));

        //超时时间设置，默认60秒
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

        //自动管理cookie（或者叫session的保持），以下几种任选其一就行
        //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));              //使用数据库保持cookie，如果cookie不过期，则一直有效
        //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie，app退出后，cookie消失


        // 其他统一的配置
        // 详细说明看GitHub文档：https://github.com/jeasonlzy/
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //建议设置OkHttpClient，不设置会使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3);                             //全局统一超时重连次数，默认为三次，那么最差的情况会请求4次(一次原始请求，三次重连请求)，不需要可以设置为0
//                .addCommonHeaders(headers)                      //全局公共头
//                .addCommonParams(params);                       //全局公共参数
    }

    public static HttpLoggingInterceptor getHttpLoggingInterceptor() {
        return loggingInterceptor;
    }

    private void initLog() {
        LogUtils.Config config = LogUtils.getConfig()
                .setLogSwitch(isDebug)// 设置 log 总开关，包括输出到控制台和文件，默认开
                .setConsoleSwitch(isDebug)// 设置是否输出到控制台开关，默认开
                .setGlobalTag("WKK")// 设置 log 全局标签，默认为空
                // 当全局标签不为空时，我们输出的 log 全部为该 tag，
                // 为空时，如果传入的 tag 为空那就显示类名，否则显示 tag
                .setLogHeadSwitch(true)// 设置 log 头信息开关，默认为开
                .setLog2FileSwitch(false)// 打印 log 时是否存到文件的开关，默认关
                .setFileExtension(".log")// 设置日志文件后缀
                .setBorderSwitch(true)// 输出日志是否带边框开关，默认开
                .setSingleTagSwitch(true)// 一条日志仅输出一条，默认开，为美化 AS 3.1 的 Logcat
                .setConsoleFilter(LogUtils.V)// log 的控制台过滤器，和 logcat 过滤器同理，默认 Verbose
                .setFileFilter(LogUtils.V)// log 文件过滤器，和 logcat 过滤器同理，默认 Verbose
                .setStackDeep(1)// log 栈深度，默认为 1
                .setStackOffset(0)// 设置栈偏移，比如二次封装的话就需要设置，默认为 0
                .setSaveDays(3);// 设置日志可保留天数，默认为 -1 表示无限时长
        // 新增 ArrayList 格式化器，默认已支持 Array, Throwable, Bundle, Intent 的格式化输出
//                .addFormatter(new LogUtils.IFormatter<ArrayList>() {
//                    @Override
//                    public String format(ArrayList arrayList) {
//                        return "LogUtils Formatter ArrayList { " + arrayList.toString() + " }";
//                    }
//                });
//        LogUtils.i(config.toString());
    }


    //选择图片监听日志初始化
    private void PictureSelector() {
        // PictureSelector 绑定监听用户获取全局上下文或其他...
        PictureAppMaster.getInstance().setApp(this);
        // PictureSelector Crash日志监听
//        PictureSelectorCrashUtils.init(new PictureSelectorCrashUtils.CrashAppListener() {
//            @Override
//            public void onFinishApp(Thread t, Throwable e) {
//
//            }
//        });
    }

    public static PictureSelectionModel getPictureSelectionModel() {
        return selectionModel;
    }

    public static PictureSelectionCameraModel getPictureSelectionCameraModel() {
        return cameraModel;
    }

    public static PictureSelectionPreviewModel getPictureSelectionPreviewModel() {
        return previewModel;
    }

    public static int getChooseMode() {
        return chooseMode;
    }

    public static void setChooseMode(int chooseMode) {
        BaseApplication.chooseMode = chooseMode;
    }

    /**
     * 初始化相册选择器
     */
    public static void initPhotoSelector(Activity activty, int maxSelectNum, boolean isMultiple, boolean isSelectionModel) {
        //modle: true 相册   false 相机
        if (isSelectionModel) {
            selectionModel = PictureSelector.create(activty)
                    .openGallery(getChooseMode())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .setImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                    .setCompressEngine(new ImageFileCompressEngine())
                    .setVideoPlayerEngine(new IjkPlayerEngine())
                    .setSelectorUIStyle(selectorStyle)// 动态自定义相册主题
                    .isMaxSelectEnabledMask(true)// 选择数到了最大阀值列表是否启用蒙层效果
                    .setMaxSelectNum(maxSelectNum)// 最大图片选择数量
                    .setMinSelectNum(1)// 最小选择数量
                    .setMaxVideoSelectNum(1) // 视频最大选择数量
                    .setMinVideoSelectNum(1)// 视频最小选择数量
                    .setImageSpanCount(4)// 每行显示个数
                    .isEmptyResultReturn(false)// 支持未选择返回
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 设置相册Activity方向，不设置默认使用系统
                    .setSelectionMode(isMultiple ? SelectModeConfig.MULTIPLE : SelectModeConfig.SINGLE)// 多选 or 单选
                    .isDirectReturnSingle(true)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                    .isPreviewImage(true)// 是否可预览图片
                    .isPreviewVideo(true)// 是否可预览视频
                    .isPreviewAudio(false) // 是否支持音频预览
                    .isGif(false)// 是否显示gif图片
                    .setRecordVideoMinSecond(15)
                    .isSelectZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .setVideoQuality(VideoQuality.VIDEO_QUALITY_LOW)
                    .isOpenClickSound(false);// 是否开启点击声音


        } else {
            // 单独拍照
            boolean isCompress = false;
            CompressFileEngine compressFileEngine = isCompress ? new ImageFileCompressEngine() : null;
            cameraModel = PictureSelector.create(activty)
                    .openCamera(getChooseMode())
                    .setCompressEngine(compressFileEngine)
                    .setSandboxFileEngine(new MeSandboxFileEngine())
                    .setAddBitmapWatermarkListener(new MeBitmapWatermarkEventListener(PathUtils.getExternalPicturesPath()))
                    .isOriginalControl(false) //是否开启原图功能，需要结合setSandboxFileEngine使用
                    .setRecordVideoMaxSecond(15);
        }

    }

    /**
     * 图片视频预览模式
     *
     * @param activty
     */
    public static void initPreviewModel(Activity activty) {
        previewModel = PictureSelector.create(activty)
                .openPreview()
                .setImageEngine(GlideEngine.createGlideEngine())
                .setVideoPlayerEngine(new ExoPlayerEngine())
                .setSelectorUIStyle(selectorStyle)
                .isAutoVideoPlay(true)
                .isEnableVideoSize(false)
                .isLoopAutoVideoPlay(false)
                .isPreviewFullScreenMode(true)
                .isVideoPauseResumePlay(true);
    }


    /**
     * 自定义压缩
     */
    private static class ImageFileCompressEngine implements CompressFileEngine {

        @Override
        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
            Luban.with(context).load(source).ignoreBy(100).setRenameListener(new OnRenameListener() {
                @Override
                public String rename(String filePath) {
                    int indexOf = filePath.lastIndexOf(".");
                    String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".jpg";
                    return DateUtils.getCreateFileName("CMP_") + postfix;
                }
            }).setCompressListener(new OnNewCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String source, File compressFile) {
                    if (call != null) {
                        call.onCallback(source, compressFile.getAbsolutePath());
                    }
                }

                @Override
                public void onError(String source, Throwable e) {
                    if (call != null) {
                        call.onCallback(source, null);
                    }
                }
            }).launch();
        }
    }

    /**
     * 自定义沙盒文件处理
     */
    private static class MeSandboxFileEngine implements UriToFileTransformEngine {

        @Override
        public void onUriToFileAsyncTransform(Context context, String srcPath, String mineType, OnKeyValueResultCallbackListener call) {
            if (call != null) {
                call.onCallback(srcPath, SandboxTransformUtils.copyPathToSandbox(context, srcPath, mineType));
            }
        }
    }

    /**
     * 给图片添加水印
     */
    private static class MeBitmapWatermarkEventListener implements OnBitmapWatermarkEventListener {
        private final String targetPath;

        public MeBitmapWatermarkEventListener(String targetPath) {
            this.targetPath = targetPath;
        }

        @Override
        public void onAddBitmapWatermark(Context context, String srcPath, String mimeType, OnKeyValueResultCallbackListener call) {
            if (PictureMimeType.isHasHttp(srcPath) || PictureMimeType.isHasVideo(mimeType)) {
                // 网络图片和视频忽略，有需求的可自行扩展
                call.onCallback(srcPath, "");
            } else {
                // 暂时只以图片为例
                Glide.with(context).asBitmap().sizeMultiplier(0.6F).load(srcPath).into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
//                        Bitmap watermark = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_mark_win);
//                        Bitmap watermarkBitmap = ImageUtil.createWaterMaskRightTop(context, resource, watermark, 0, 15);
                        String time = TimeUtils.getNowString();
                        String lat = SPStaticUtils.getString(SPTools.lat); //纬度
                        String lng = SPStaticUtils.getString(SPTools.lng); //经度


                        TextView textView = new TextView(context);
                        textView.setText("时间：" + time + "\n" + "经度：" + lng + "\n" + "纬度：" + lat);
                        textView.setTextColor(context.getResources().getColor(R.color.white));
                        textView.setTextSize(15);
                        textView.setTypeface(Typeface.DEFAULT_BOLD);
                        Bitmap watermark = ImageUtil.viewToBitmap(textView);

                        Bitmap watermarkBitmap = ImageUtil.createWaterMaskLeftTop(context, resource, watermark, 15, 15);


                        watermarkBitmap.compress(Bitmap.CompressFormat.JPEG, 60, stream);
                        watermarkBitmap.recycle();
                        FileOutputStream fos = null;
                        String result = null;
                        try {
                            File targetFile = new File(targetPath, DateUtils.getCreateFileName("Mark_") + ".jpg");
                            fos = new FileOutputStream(targetFile);
                            fos.write(stream.toByteArray());
                            fos.flush();
                            result = targetFile.getAbsolutePath();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            PictureFileUtils.close(fos);
                            PictureFileUtils.close(stream);
                        }
                        if (call != null) {
                            call.onCallback(srcPath, result);
                        }
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        if (call != null) {
                            call.onCallback(srcPath, "");
                        }
                    }
                });
            }
        }
    }


    /**
     * 设置相册主题
     */
    private void setDefaultStyle() {
        // 相册主题
        selectorStyle = new PictureSelectorStyle();
        SelectMainStyle numberSelectMainStyle = new SelectMainStyle();
        numberSelectMainStyle.setSelectNumberStyle(true);
        numberSelectMainStyle.setPreviewSelectNumberStyle(false);
        numberSelectMainStyle.setPreviewDisplaySelectGallery(true);
        numberSelectMainStyle.setSelectBackground(R.drawable.ps_default_num_selector);
        numberSelectMainStyle.setPreviewSelectBackground(R.drawable.ps_preview_checkbox_selector);
        numberSelectMainStyle.setSelectNormalBackgroundResources(R.drawable.ps_select_complete_normal_bg);
        numberSelectMainStyle.setSelectNormalTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_53575e));
        numberSelectMainStyle.setSelectNormalText(getString(R.string.ps_send));
        numberSelectMainStyle.setAdapterPreviewGalleryBackgroundResource(R.drawable.ps_preview_gallery_bg);
        numberSelectMainStyle.setAdapterPreviewGalleryItemSize(DensityUtil.dip2px(getContext(), 52));
        numberSelectMainStyle.setPreviewSelectText(getString(R.string.ps_select));
        numberSelectMainStyle.setPreviewSelectTextSize(14);
        numberSelectMainStyle.setPreviewSelectTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_white));
        numberSelectMainStyle.setPreviewSelectMarginRight(DensityUtil.dip2px(getContext(), 6));
        numberSelectMainStyle.setSelectBackgroundResources(R.drawable.ps_select_complete_bg);
        numberSelectMainStyle.setSelectText(getString(R.string.ps_send_num));
        numberSelectMainStyle.setSelectTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_white));
        numberSelectMainStyle.setMainListBackgroundColor(ContextCompat.getColor(getContext(), R.color.ps_color_black));
        numberSelectMainStyle.setCompleteSelectRelativeTop(true);
        numberSelectMainStyle.setPreviewSelectRelativeBottom(true);
        numberSelectMainStyle.setAdapterItemIncludeEdge(false);

        // 头部TitleBar 风格
        TitleBarStyle numberTitleBarStyle = new TitleBarStyle();
        numberTitleBarStyle.setHideCancelButton(true);
        numberTitleBarStyle.setAlbumTitleRelativeLeft(true);
        numberTitleBarStyle.setTitleAlbumBackgroundResource(R.drawable.ps_album_bg);
        numberTitleBarStyle.setTitleDrawableRightResource(R.drawable.ps_ic_grey_arrow);
        numberTitleBarStyle.setPreviewTitleLeftBackResource(R.drawable.ps_ic_normal_back);

        // 底部NavBar 风格
        BottomNavBarStyle numberBottomNavBarStyle = new BottomNavBarStyle();
        numberBottomNavBarStyle.setBottomPreviewNarBarBackgroundColor(ContextCompat.getColor(getContext(), R.color.ps_color_half_grey));
        numberBottomNavBarStyle.setBottomPreviewNormalText(getString(R.string.ps_preview));
        numberBottomNavBarStyle.setBottomPreviewNormalTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_9b));
        numberBottomNavBarStyle.setBottomPreviewNormalTextSize(16);
        numberBottomNavBarStyle.setCompleteCountTips(false);
        numberBottomNavBarStyle.setBottomPreviewSelectText(getString(R.string.ps_preview_num));
        numberBottomNavBarStyle.setBottomPreviewSelectTextColor(ContextCompat.getColor(getContext(), R.color.ps_color_white));


        selectorStyle.setTitleBarStyle(numberTitleBarStyle);
        selectorStyle.setBottomBarStyle(numberBottomNavBarStyle);
        selectorStyle.setSelectMainStyle(numberSelectMainStyle);

    }

    public class OwnUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

        @Override
        public void uncaughtException(@NonNull Thread t, @NonNull Throwable e) {
            StackTraceElement[] elements = e.getStackTrace();

            StringBuilder reason = new StringBuilder(e.toString());

            if (elements != null && elements.length > 0) {

                for (StackTraceElement element : elements) {

                    reason.append("\n");
                    reason.append(element.toString());
                }
            }

            MyLogUtil.e("uncaughtException", reason.toString());
            android.os.Process.killProcess(android.os.Process.myPid());

        }
    }

    /**
     * 初始化自动更新框架
     */
    public void initUpdate() {
        XUpdate.get()
                .debug(true)
                .isWifiOnly(false)                                               //默认设置只在wifi下检查版本更新
                .isGet(true)                                                    //默认设置使用get请求检查版本
                .isAutoMode(false)                                              //默认设置非自动模式，可根据具体使用配置
                .param("versionCode", UpdateUtils.getVersionCode(this))         //设置默认公共请求参数
                .param("appKey", getPackageName())
                .setOnUpdateFailureListener(new OnUpdateFailureListener() {     //设置版本更新出错的监听
                    @Override
                    public void onFailure(UpdateError error) {
                        int code = error.getCode();
                        if (code > 2004) {          //对不同错误进行处理
//                            MyLogUtil.e("XUpdate", "error==" + error.getCode() + "," + error.toString());
                            String log = "XUpdate onFailure:" + "error=" + error.getCode() + "," + error.toString();
                            if (log.length() > 1000) {
                                log = log.substring(0, 1000);
                            }
                            uploadAppLogs(log);
                        }

                    }
                })
                .supportSilentInstall(true)                                     //设置是否支持静默安装，默认是true
                .setIUpdateHttpService(new OKHttpUpdateHttpService())           //这个必须设置！实现网络请求功能。
                .init(this);

        XUpdate.get().setILogger(new ILogger() {
            @Override
            public void log(int priority, String tag, String message, Throwable t) {
                //实现日志记录功能
                MyLogUtil.e("XUpdate", "tag==" + tag + "\n message==" + message + "\n priority==" + priority);
                if (t != null) {
                    String log = "XUpdate log:" + "priority=" + priority + ",tag=" + tag + ",message=" + message + ",throwable=" + t;
                    if (log.length() > 1000) {
                        log = log.substring(0, 1000);
                    }
                    uploadAppLogs(log);
                }


            }
        });

    }

    public BaseActivity getTopActivity() {
        return baseActivity;
    }


    /**
     * 上报异常日志
     */

    public void uploadAppLogs(String errorLog) {
        BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
        String deviceName = myDevice.getName();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("appVersion", "v" + AppUtils.getAppVersionName());
        hashMap.put("mobileModel", deviceName);
        hashMap.put("osVersion", "Android" + DeviceUtils.getSDKVersionName());
        hashMap.put("errorLog", errorLog);
        String str = GsonUtils.toJson(hashMap);

//        if (baseActivity != null) {
//            OkGo.<String>post(Constant.getInstance().POST_APP_LOGS)
//                    .tag(this)
//                    .upJson(str)
//                    .execute(new StringDialogCallback(baseActivity) {
//                        @Override
//                        public void onSuccess(Response<String> response) {
//                            String result = response.body();
//                            if (!StringUtils.isEmpty(result)) {
//
//
//                            }
//                        }
//
//                        @Override
//                        public void onError(Response<String> response) {
//                            String result = response.body();
//                            MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
//                        }
//                    });
//        }
    }


//    public ReportedEventDao getReportedEventDao() {
//        return reportedEventDao;
//    }
//
//    public void setReportedEventDao(ReportedEventDao reportedEventDao) {
//        this.reportedEventDao = reportedEventDao;
//    }


}
